﻿
//显示加载过程 use: var loader=new Loader();
function Loader(target) {
    this.element = target == null ? $(document.body) : $(target);
    this.show = function () {
        kendo.ui.progress(this.element, true);
    }
    this.hide = function () {
        kendo.ui.progress(this.element, false);
    }
}
function showLoader() {
    if (window != window.top) {
        if (window.top.showLoader) {
            return window.top.showLoader();
        }
    }
    kendo.ui.progress($("#loading"), true);
}
function hideLoader() {
    if (window != window.top) {
        if (window.top.hideLoader) {
            return window.top.hideLoader();
        }
    }
    kendo.ui.progress($("#loading"), false);
}
//by calvin
//2015.4.23 点击修改浏览器地址栏
function changeManageUrlBar(url, obj) {
    try {
        if (url == '' && obj) {
            url = $.trim($(obj).attr('href'));
        }
        var stateObject = {};
        var title = "";
        //alert(url);
        var newUrl = "/Manage/?" + url;
        history.pushState(stateObject, title, newUrl);
        showLoader();
    }
    catch (exception) {
    }
    finally {
    }
}

//add kevin 2016-5-13 11:21:47
//全局跳转
function urlJump(url,home,params,currentPage) {
    if (url == undefined) {
        url = "";
    } else if (url.indexOf("/") > 0) {
        url = "/" + url;
    }
    var jumpSystem = "";

    var curUrl = window.location.href.toLowerCase();
    var curOrigin = (window.location.origin || window.location.host).toLowerCase();

    //公司后台管理系统
    if (curUrl.indexOf(curOrigin + "/manage/") > -1) {
        jumpSystem = "/Manage";
    }
        //平台后台管理系统
    else if (curUrl.indexOf(curOrigin + "/admin/") > -1) {
        jumpSystem = "/Admin";
    }
    if (home) {
        //var routes = url.split('/');
        //routes = $.grep(routes, function(i, o) {
        //    return o != "" && o != null;
        //});
        if (top.window.defaultHeadFunc !=undefined) {
            top.window.defaultHeadFunc.loader.show();
        }

        var redirect = "?page=" + url + (params == null ? "" : params);
        if (currentPage) {
            currentPage.parent.location.href = jumpSystem + "/" + home + "/index" + redirect;
        } else {
            window.location.href = jumpSystem + "/" + home + "/index" + redirect;
        }
    } else {
        if (parent.SubIFrameFunc != undefined) {
            parent.SubIFrameFunc.loader.show();
        }
        window.location.href = jumpSystem + url;
    }

    var historyUrl = top.location.href.indexOf('?')>0?top.location.href.substr(top.location.href.indexOf('?')+1):'';
    var urlParams = historyUrl.split('&');
    var newUrl = "";
    var hasPage = false;
    $.each(urlParams, function (i, value) {
        if (value != "") {
            if (value.indexOf("page=")>=0) {
                value = "page=" + jumpSystem + url;
                hasPage = true;
            }
            newUrl += ((newUrl == "" ? "?" : "&") + value);
        }
    });
    if (!hasPage) newUrl += ((newUrl == "" ? "?" : "&") + "page=" + jumpSystem + url);
    top.window.defaultHeadFunc.HistoryPush(newUrl);
}

//by hewang
//2015.6.29 点击修改图片
function changeImg(obj) {
    var imgsrc = $(obj).find("img").attr("src");
    var imgLastdot = imgsrc.lastIndexOf('.');
    var imgnum = imgsrc.substring(imgLastdot - 1, imgLastdot);
    var ishave = $(obj).parent().hasClass("k-state-active");
    $(".parentimg").each(function () {
        $(this).attr("src", $(this).attr("src").replace('1', '0'));
    });
    if (ishave)//改成灰色
    {
        if (imgnum != '0') {
            imgsrc = imgsrc.replace('1', '0');
        }
    } else {
        if (imgnum == '0') {
            imgsrc = imgsrc.replace('0', '1');
        }
    }

    $(obj).find("img").attr("src", imgsrc);
}

//导航栏mouseoover事件，
function img_over_a(obj) {
    if (!$(obj).parent().hasClass("k-state-active")) {
        $(obj).find("img").attr("src", $(obj).find("img").attr("src").replace('0', '1'));
    }
    else {
        $(obj).find("img").attr("src", $(obj).find("img").attr("src").replace('1', '0'));
    }
}
//导航栏mouseout事件
function img_out_a(obj) {
    if (!$(obj).parent().hasClass("k-state-active")) {
        $(obj).find("img").attr("src", $(obj).find("img").attr("src").replace('1', '0'));
    } else {
        $(obj).find("img").attr("src", $(obj).find("img").attr("src").replace('0', '1'));
    }
}
/*编码&解码*/
//by lurg 2015.04.29
function htmlEncode(value) {
    return $("<div/>").text(value).html();
}
function htmlDecode(value) {
    return $("<div/>").html(value).text();
}


//对象深复制
function clone(target) {
    var buf;
    if (target instanceof Array) {
        buf = [];  //创建一个空的数组 
        var i = target.length;
        while (i--) {
            buf[i] = clone(target[i]);
        }
        return buf;
    } else if (target instanceof Object) {
        buf = {};  //创建一个空对象 
        for (var k in target) {  //为这个对象添加新的属性 
            buf[k] = clone(target[k]);
        }
        return buf;
    } else {

        return target;
    }
}

//封装Mova控件
(function ($) {
    $.fn.extend({
        /*  在textarea处插入文本--Start */
        insertContent: function (myValue, t) {
            var $t = $(this)[0];
            if (document.selection) { // ie  
                this.focus();
                var sel = document.selection.createRange();
                sel.text = myValue;
                this.focus();
                sel.moveStart('character', -l);
                var wee = sel.text.length;
                if (arguments.length == 2) {
                    var l = $t.value.length;
                    sel.moveEnd("character", wee + t);
                    t <= 0 ? sel.moveStart("character", wee - 2 * t
                        - myValue.length) : sel.moveStart(
                        "character", wee - t - myValue.length);
                    sel.select();
                }
            } else if ($t.selectionStart
                || $t.selectionStart == '0') {
                var startPos = $t.selectionStart;
                var endPos = $t.selectionEnd;
                var scrollTop = $t.scrollTop;
                $t.value = $t.value.substring(0, startPos)
                    + myValue
                    + $t.value.substring(endPos,
                        $t.value.length);
                this.focus();
                $t.selectionStart = startPos + myValue.length;
                $t.selectionEnd = startPos + myValue.length;
                $t.scrollTop = scrollTop;
                if (arguments.length == 2) {
                    $t.setSelectionRange(startPos - t,
                        $t.selectionEnd + t);
                    this.focus();
                }
            } else {
                this.value += myValue;
                this.focus();
            }
        },
        //封装Mova日期控件
        movaDateTimePicker: function (options) {
            var settings = $.extend({
                format: "yyyy-MM-dd HH:mm",
                mask: "0000-00-00 00:00",
                value: $(this).val(),
                min:new Date("1900/01/01")
            }, options);
            return this.kendoDateTimePicker({
                format: settings.format,
                value: settings.value == null ? new Date() : $.convertToDate(settings.value),
                min: settings.min
            })
                .kendoMaskedTextBox({
                    mask: settings.mask
                })
                .blur(function () {
                    if ($.trim(this.value) && $.convertToDate(this.value) == "Invalid Date") {
                        this.value = "";
                    }
                });
        },
        movaDatePicker: function (options) {
            var settings = $.extend({
                format: "yyyy-MM-dd",
                mask: "0000-00-00",
                value: $(this).val(),
                min: new Date("1900/01/01")
            }, options);
            return this.kendoDatePicker({
                format: settings.format,
                value: settings.value == null ? new Date() : $.convertToDate(settings.value),
                min:settings.min
            })
                .kendoMaskedTextBox({
                    mask: settings.mask
                })
                .blur(function () {
                    if ($.trim(this.value) && $.convertToDate(this.value) == "Invalid Date") {
                        this.value = "";
                    }
                });
        },
        movaDorpDownList: function (options) {
            var settings = $.extend({
                dataTextField: "text",
                dataValueField: "value",
                dataSource: null,
                value: 0
            }, options);
            return this.kendoDropDownList({
                dataTextField: settings.dataTextField,
                dataValueField: settings.dataValueField,
                dataSource: settings.dataSource,
                value: settings.value == null ? 1 : settings.value
            });
        },
        movaRadio: function (value) {
            if (value == undefined || value == "") {
                $(this[0]).prop("checked", true);
            } else {
                this.each(function () {
                    if ($(this).val() == value) {
                        $(this).prop("checked", true);
                        return false;
                    }
                });
            }
        },
        movaChecker: function (options) {
            var settings = $.extend({
                value: false,
                label_on: "已启用",
                label_off: "未启用",
                onClick: null
            }, options);

            var self = this;
            var checker = {};
            var _class = settings.value ? "m-check-on" : "m-check-off";
            $(self).addClass(_class);

            var _id = $(self).attr("id");
            if (!$(self).next('span.ck-label').length) {
                $(self).after('<span class="ck-label tset"></span>');
            }
            var _lable = $(self).next('span.ck-label');
            _lable.text(settings.value ? settings.label_on : settings.label_off);

            var _hidden;
            if ($.trim(_id)) {
                if (!$('input[type="hidden"][name="' + _id + '"]').length) {
                    $(self).before('<input type="hidden" name="' + _id + '"/>');
                }
                _hidden = $('input[type="hidden"][name="' + _id + '"]');
            }

            //选中事件
            function check() {
                $(self).attr('class', 'm-check-on');
                _lable.text(settings.label_on);
                settings.value = true;
                if (_hidden) {
                    $('input[type="hidden"][name="' + _id + '"]').val('1');
                }
            }

            //取消事件
            function uncheck() {
                $(self).attr('class', 'm-check-off');
                _lable.text(settings.label_off);
                settings.value = false;
                if (_hidden) {
                    $('input[type="hidden"][name="' + _id + '"]').val('0');
                }
            }

            ///获取值、设置值
            checker.val = function (value) {
                if (value == null) {
                    return settings.value;
                }
                else if (value === true) {
                    check();
                }
                else if (value === false) {
                    uncheck();
                }
            }

            //点击事件
            $(self).bind("click", function () {
                var chked = $(self).attr('class').indexOf('m-check-on') >= 0;
                if (chked) {
                    uncheck();
                }
                else {
                    check();
                }
                //自定义事件
                if (settings.onClick) {
                    settings.onClick(self, settings.value);
                }
            });

            return checker;
        }
    });
})(jQuery);

//取值函数
var movaUI =
{
    getDDLValue: function (id) {
        return $("#" + id).data("kendoDropDownList").value();
    },
    getDTPValue: function (id) {
        return $("#" + id).data("kendoDateTimePicker").value();
    },
    getRadioValue: function (name) {
        return $(":radio[name='" + name + "']:checked").val();
    }
};

//封装Mova方法
(function ($) {
    $.extend({
        //转换日期时间(兼容旧IE)
        convertToDate: function (value) {
            if (value == "") return "Invalid Date";
            if (value instanceof Date) return new Date(value);
            if (value.indexOf("-")>0 && (navigator.userAgent.indexOf("MSIE") > 0 || navigator.userAgent.indexOf("rv:") > 0)){
                var r = new Date();
                var ds = value.split(" ")[0].split("-");
                r.setFullYear(ds[0], ds[1] - 1, ds[2]);
                if (value.split(" ").length > 1) {
                    var ts = value.split(" ")[1].split(":");
                    r.setHours((ts[0] == null ? 0 : ts[0]), (ts[1] == null ? 0 : ts[1]), (ts[2] == null ? 0 : ts[2]), 0);
                }
                return r;
            } else {
                value = value.replace(/\-/g, "/");
                return new Date(value);
            }
        },
        toStr: function (obj) {
            return obj == null ? '' : '' + obj;
        },
        fromJSONDate: function (value) {
            if (!value) return null;
            //使用正则表达式将生日属性中的非数字（\D）删除
            //并把得到的毫秒数转换成数字类型
            var date = parseInt(value.replace(/\D/igm, ""));
            //实例化一个新的日期格式，使用1970 年 1 月 1 日至今的毫秒数为参数
            return new Date(date);
        },
        movaGuid: function () {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        },
        movaForm: function(options) {
            var setting=$.extend({
                action: "",
                method: "POST",
                params: []
            }, options);

            var form = $('<form>');
            form.attr("action", setting.action);
            form.attr("method", setting.method);
            $.each(setting.params, function(i, dataitem) {
                form.append('<input type="hidden" name="' + dataitem.name + '" value="' + dataitem.value + '" />');
            });

            form.ajaxSubmit = function (success,beforsend, error) {
                $me = $(this);
                $me.ajaxSubmit({
                    beforeSubmit: function() {
                        if ($.isFunction(beforsend)) {
                            beforsend();
                        }
                    },
                    success: function(data) {
                        if ($.isFunction(success)) {
                            success(data);
                        }
                    },
                    error: function(sender, status, errorMsg) {
                        if ($.isFunction(error)) {
                            error(sender, status, errorMsg);
                        }
                    },
                    url: $me.attr("action"),
                    type: $me.attr("method"),
                    dataType: "json",
                    timeout: 60000
                });
            };

            return form;
        }
    });
})(jQuery);

(function compatibilityAdjust() {
    if (String.prototype.startsWith == undefined) {
        String.prototype.startsWith = function (str) {
            if (typeof (str) != 'string') {
                return false;
            }
            else {
                return this.substr(0, str.length) == str;
            }
        }
    }
})();

String.prototype.endWith = function (s) {
    if (s == null || s == "" || this.length == 0 || s.length > this.length)
        return false;
    if (this.substring(this.length - s.length) == s)
        return true;
    else
        return false;
    return true;
}

String.prototype.startWith = function (s) {
    if (s == null || s == "" || this.length == 0 || s.length > this.length)
        return false;
    if (this.substr(0, s.length) == s)
        return true;
    else
        return false;
    return true;
}

Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1,                 //月份 
        "d+": this.getDate(),                    //日 
        "h+": this.getHours(),                   //小时 
        "m+": this.getMinutes(),                 //分 
        "s+": this.getSeconds(),                 //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds()             //毫秒 
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
//xurui 2015-10-09
//取子字符串
//中文按两个字节算
function subChineseString(TargetStr, StartIndex, TotalLength) {
    if (typeof (TargetStr) != "string") {
        return TargetStr;
    }
    var regep = /^[\u4e00-\u9fa5]$/g;
    var StartResult = TargetStr.substr(StartIndex);

    var sumLength = 0;
    var realLength = 0;

    //转化为数组
    var ResultArr = [].slice.apply(StartResult);

    for (var i in ResultArr) {
        regep = /^[\u4e00-\u9fa5]$/g;
        if (regep.test(StartResult[i])) {
            sumLength += 2;
        }
        else {
            sumLength += 1;
        }
        if (sumLength >= TotalLength) {
            if (i != StartResult.length - 1) {
                var ret = StartResult.substr(0, Number(i) + 1);
                return ret + '...';
            }
            else {
                return StartResult;
            }
        }
    }
    return StartResult;

}


/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat = function () {
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
		    val = String(val);
		    len = len || 2;
		    while (val.length < len) val = "0" + val;
		    return val;
		};

    // Regexes and supporting functions are cached through closure
    return function (date, mask, utc) {
        var dF = dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date;
        if (isNaN(date)) throw SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }

        var _ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
			    d: d,
			    dd: pad(d),
			    ddd: dF.i18n.dayNames[D],
			    dddd: dF.i18n.dayNames[D + 7],
			    m: m + 1,
			    mm: pad(m + 1),
			    mmm: dF.i18n.monthNames[m],
			    mmmm: dF.i18n.monthNames[m + 12],
			    yy: String(y).slice(2),
			    yyyy: y,
			    h: H % 12 || 12,
			    hh: pad(H % 12 || 12),
			    H: H,
			    HH: pad(H),
			    M: M,
			    MM: pad(M),
			    s: s,
			    ss: pad(s),
			    l: pad(L, 3),
			    L: pad(L > 99 ? Math.round(L / 10) : L),
			    t: H < 12 ? "a" : "p",
			    tt: H < 12 ? "am" : "pm",
			    T: H < 12 ? "A" : "P",
			    TT: H < 12 ? "AM" : "PM",
			    Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
			    o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
			    S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

        return mask.replace(token, function ($0) {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
}();

// Some common format strings
dateFormat.masks = {
    "default": "ddd mmm dd yyyy HH:MM:ss",
    shortDate: "m/d/yy",
    mediumDate: "mmm d, yyyy",
    longDate: "mmmm d, yyyy",
    fullDate: "dddd, mmmm d, yyyy",
    shortTime: "h:MM TT",
    mediumTime: "h:MM:ss TT",
    longTime: "h:MM:ss TT Z",
    isoDate: "yyyy-mm-dd",
    isoTime: "HH:MM:ss",
    isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
    ],
    monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
    ]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
    return dateFormat(this, mask, utc);
};

function movaParseDate(date) {
    return dateFormat(date, 'isoUtcDateTime');
}



//xurui 2015-08-27
//前台弹窗下载
//部分实现
function movasavepic(fileURL) {
    var win = window.open('http://' + window.location.host + fileURL, "_blank",
        "height=0,width=0,toolbar=no,menubar=no,scrollbars=no,resizable=on,location=no,status=no");
    win.document.execCommand("SaveAs");
}

//lurg 2015/10/08
//Cookie操作
function setCookie(name, value, expires)//名称，值，过期时间（分钟）
{
    var exp = new Date();
    exp.setTime(exp.getTime() + expires * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}
function getCookie(name)//取cookies函数        
{
    var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
    if (arr != null) return unescape(arr[2]); return null;

}
function delCookie(name)//删除cookie
{
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null) document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}

//获取URL参数
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}